<?php

namespace App\Model;
use Hash;
use DB;

class AdminUser extends Model{

	protected $table = 'admin_user';

    protected $primaryKey = 'admin_id';

    protected $guarded = [];

    public $timestamps = false;

    /* 添加/修改密码时自动加密 */
    public function setPasswordAttribute($value){
        $this->attributes['password'] = Hash::make($value);
    }


    /* 根据用户账号密码获取用户信息 */
    public function getUserByPsd($username , $password){
    	$info = $this->where('username',$username)->first();

    	if(is_object($info)){
    		if($info->status == 0){
    			$this->error = '用户被禁用！';
    			return false;
    		}

    		if(!Hash::check($password , $info->password)){
    			$this->error = '用户密码不正确！';
    			return false;
    		}
    		return $info;
    	}else{
    		$this->error = '用户不存在！';
    		return false;
    	}
    }

    /**
     * 获取用户权限角色
     * @return array 数组
     */
    public function getUserRole($admin_id){

        $roles = DB::table('admin_role as r')
            ->join('admin_user_role as ur','r.role_id','ur.role_id')
            ->where([
                ['ur.admin_id','=',$admin_id],
                ['r.status','=',1]
            ])
            ->select(['r.name','r.role_id','r.rule_id'])
            ->get()->toArray();


        if($roles){
            $roles = array_map(function($el){
                return (array) $el;
            }, $roles);

            return $roles;
        }

        return [];
    }

    /**
     * 获取用户rule_id
     * @param  [type] $admin_id [description]
     * @return [array]           [description]
     */
    public function getUserRuleId($admin_id){
        $roles = $this->getUserRole($admin_id);

        $rule_ids = array_column($roles, 'rule_id');

        if(is_empty($rule_ids)) return [];

        //将['1,3,6,4','1,6,8,7']生成类似格式1,3,6,4,1,6,8,7的id字符串
        $rule_ids = implode(',', $rule_ids);

        //z再次转换成数组并且去重
        $rule_ids = explode(',', $rule_ids);
        $rule_ids = array_unique($rule_ids);

        return $rule_ids;
    }
}